package com.ty.service.imple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mysql.fabric.xmlrpc.base.Array;
import com.ty.dao.BaseDaoI;
import com.ty.entity.SysAdmin;
import com.ty.entity.SysMenus;
import com.ty.entity.SysRole;
import com.ty.entity.SysUserRole;
import com.ty.service.MenusService;
import com.ty.util.Pager;

@Service
public class MenusServiceImple implements MenusService {

	@Autowired
	private BaseDaoI<SysMenus> dao;
	
	@Autowired
	private BaseDaoI<SysRole> roleDao;
	
	@Autowired
	private BaseDaoI<SysUserRole> userRoleDao;
	
	@Override
	public Pager selectByPager(int pageNum, int pageSize, SysMenus menus) {
		//查询条件
		Map<String,Object> params=new HashMap<>();
				
		String hql="from SysMenus o ";
		String countHql="select count(o) "+hql;
		
		String where=" where 1=1 ";
		
		if(menus.getSysMenus()!=null&&!"".equals(menus.getSysMenus().getId())&&menus.getSysMenus().getId().intValue()>0) {
			where+="  and o.sysMenus.id="+menus.getSysMenus().getId();
		}else {
			where+=" and o.sysMenus is null";
		}
		
		if(menus!=null&&menus.getName()!=null&&!"".equals(menus.getName())) {
			where+=" and o.name=:name";
			params.put("name", menus.getName());
		}
		
		hql+=where+" order by o.orderSort asc ";
		countHql+=where;
		
		Pager page=new Pager();
		//获取总行数
		page.setTotalCount(dao.count(countHql,params).intValue());
		//获取总页数
		page.setPageSize(pageSize);
		page.setCurrentPageIndex(pageNum);
		//分页查询
		List<SysMenus> list= dao.find(hql, params, page.getCurrentPageIndex(), page.getPageSize());
		page.setData(list);
		
		return page;
	}

	@Override
	public boolean deleteById(Long id) {
		try {
			SysMenus role = getById(id);
			dao.delete(role);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean updateByObj(SysMenus role) {
		try {
			dao.update(role);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public SysMenus getById(Long id) {
		String hql="from SysMenus o left join fetch o.sysMenus b where o.id="+id;
		List<SysMenus> list= dao.find(hql);
		if(list!=null&&list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public boolean deleteBatch(String ids) {
		try {
			String idArrays[] = ids.split(",");
			for (String id : idArrays) {
				this.deleteById(Long.valueOf(id));
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean saveObject(SysMenus role) {
		try {
			dao.save(role);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public String getMenus(SysMenus menus) {
		String rootHql="from SysMenus o where o.sysMenus is null order by o.orderSort asc";
		//获取到一级菜单
		List<SysMenus> list= dao.find(rootHql);
		//使用Buffered用于存储option标签
		
		int indexOf=1;
		StringBuffer sbRoot=new StringBuffer();
		sbRoot.append("<option value='0' "+checkSelected(menus,null)+" >顶级菜单</option>");
		for (SysMenus sysMenus : list) {  //循环一级菜单
			sbRoot.append("<option value='"+sysMenus.getId()+"' "+checkSelected(menus,sysMenus.getId())+">"+getNbsp(2)+"|-"+sysMenus.getName()+"</option>");
			childerMenus(sysMenus,indexOf+3,sbRoot,menus);
		}
		return sbRoot.toString();
	}
	
	/**
	 * 选择当前菜单的父级菜单
	 * @return
	 */
	private String checkSelected(SysMenus menus,Long currentId) {
		if(menus==null) {
			return "";
		}
		SysMenus pidMenus=menus.getSysMenus();
		if(pidMenus==null&&currentId==null) {
			return "selected";
		}
		
		if(pidMenus!=null&&currentId!=null&&pidMenus.getId().intValue()==currentId.intValue()) {
			return "selected";
		}
		
		
		return "";
		
	}
	
	
	/**
	 * 打印空格
	 * @return
	 */
	private String getNbsp(int index) {
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<index;i++) {
			sb.append("&nbsp;");
		}
		return sb.toString();
	}
	
	/**
	 * 获取子菜单
	 * @param rootMenus 父级菜单
	 * @param indexOf 当前的级别
	 */
	private void childerMenus(SysMenus rootMenus,int indexOf,StringBuffer sbOption,SysMenus currentMenus) {
		 String hql="from SysMenus o where o.sysMenus.id="+rootMenus.getId()+" order by o.orderSort asc";
		 //获取子菜单
		 List<SysMenus> childerMenus= dao.find(hql);
		 if(childerMenus!=null&&childerMenus.size()>0) {
			 for (SysMenus sysMenus : childerMenus) {
				 sbOption.append("<option value='"+sysMenus.getId()+"' "+checkSelected(currentMenus, sysMenus.getId())+">"+getNbsp(indexOf)+"|-"+sysMenus.getName()+"</option>");
				 int childerPid=indexOf+2;
				 childerMenus(sysMenus,childerPid,sbOption,currentMenus);
			}
		 }
	}

	@Override
	public List<Map<String, Object>> getRoleMenus(Long roleId) {
		SysRole role= roleDao.get(SysRole.class, roleId);
		String mensStr= role.getMenus();
		List<String> roleMenusData=Arrays.asList(mensStr.split(","));
		
		String hql="from SysMenus o order by o.orderSort asc ";
		List<SysMenus> mensDataList= dao.find(hql);
		List returnList=new ArrayList<>();
		for (SysMenus sysMenus : mensDataList) {
			Map<String, Object> bean=new HashMap<>();
			bean.put("id", sysMenus.getId());
			bean.put("pId", sysMenus.getSysMenus()==null?0:sysMenus.getSysMenus().getId());
			bean.put("name", sysMenus.getName());
			bean.put("checked", roleMenusData.contains(sysMenus.getId().toString())?"true":"false");
			returnList.add(bean);
		}
		
		return returnList;
	}

	@Override
	public List<SysMenus> selectByUserMenus(SysAdmin sysAdmin) {
		String userRoleHql="from SysUserRole o inner join fetch o.sysRole b   where o.sysAdmin.id="+sysAdmin.getId();
		List<SysUserRole> userRoleList= userRoleDao.find(userRoleHql);
	
		//获取角色中所有菜单编号
		Set<Long> mensSet=new HashSet<>();
		for (SysUserRole sysUserRole : userRoleList) {
			 SysRole sysRole=sysUserRole.getSysRole();
			 String strMenus=sysRole.getMenus();
			 if(strMenus==null) {
				 continue;
			 }
			 String menus[]= strMenus.split(",");
			 for (Object mensId : menus) {
				 mensSet.add(Long.valueOf(mensId.toString()));
			 }
		}
		//获取菜单的权限
		String menusHql="select o from SysMenus o where o.id in(:menusId)  and o.sysMenus is null and o.status=1 order by o.orderSort asc ";
		Query query= dao.getCurrentSession().createQuery(menusHql);
		query.setParameterList("menusId", mensSet);
		List<SysMenus>  rootList= query.list(); //获取所有菜单权限
		for (SysMenus sysMenus : rootList) {
			String childerHql="select o from SysMenus o where o.id in(:menusId)  and o.sysMenus.id="+sysMenus.getId()+" and o.status=1 order by o.orderSort asc ";
			query= dao.getCurrentSession().createQuery(childerHql);
			query.setParameterList("menusId", mensSet);
			List<SysMenus> childerMenus=query.list();
			sysMenus.setMensDataList(childerMenus);
		}
		return rootList;
	}


}
